"""
Template tags which can do retrieval of content from any model.
get_latest_objects come from: http://code.google.com/p/django-template-utils/
"""
from django import template
from django.db.models import get_model

class LatestObjectsNode(template.Node):
    def __init__(self, model, num, varname):
        self.model, self.num, self.varname = model, int(num), varname

    def render(self, context):
        model = get_model(*self.model.split('.'))
        if model is not None:
            if self.num == 1:
                context[self.varname] = model.published.all()[0]
            else:
                context[self.varname] = list(model.published.all()[:self.num])
        return ''

def do_latest_objects(parser, token):
    """
    Retrieves the latest ``num`` objects from a given model, in that
    model's default ordering, and stores them in a context variable.

    Syntax::

        {% get_latest_objects [app_name].[model_name] [num] as [varname] %}

    Example::

        {% get_latest_objects comments.freecomment 5 as latest_comments %}

    """
    bits = token.contents.split()
    if len(bits) != 5:
        raise template.TemplateSyntaxError("'%s' tag takes four arguments" % bits[0])
    if bits [3] != 'as':
        raise template.TemplateSyntaxError("third argument to '%s' tag must be 'as'" % bits[0])
    return LatestObjectsNode(bits[1], bits[2], bits[4])

def display_footer_posts(context):
    """
    Display latest posts, ``latest_posts`` var should be in the context.

    Usage::

        {% load biologeektags %}
        {% get_latest_objects journal.Post 5 as latest_posts %}
        {% display_footer_posts %}

    This will use ``display_footer_posts.html`` template.
    """
    return { 'latest_posts': context['latest_posts'] }

def display_footer_thoughts(context):
    """
    Display latest thoughts, ``latest_thoughts`` var should be in the context.

    Usage::

        {% load biologeektags %}
        {% get_latest_objects bistrot.Thought 5 as latest_thoughts %}
        {% display_footer_thoughts %}

    This will use ``display_footer_thoughts.html`` template.
    """
    return { 'latest_thoughts': context['latest_thoughts'] }

register = template.Library()
register.tag('get_latest_objects', do_latest_objects)
register.inclusion_tag('journal/display_footer_posts.html', takes_context=True)(display_footer_posts)
register.inclusion_tag('bistrot/display_footer_thoughts.html', takes_context=True)(display_footer_thoughts)
